﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Fantom.Models
{
	internal class Shapes : ObservableCollection<IShape>, IShapes
	{
		#region events

		public event SelectionEventHandler OnSelectionChanged;
		public event SelectableEventHandler OnSelectAll;
		public event SelectableEventHandler LostSelectAll;

		#endregion

		public IShape this[string shapeName] => (from shp in this.Items where shp.Name == shapeName select shp).First();

		public IApplication Application { get; set; }

		public IFantomObject Parent { get; set; }

		private HashSet<ISelectable> _selection = new HashSet<ISelectable>();

		public IEnumerable<ISelectable> Selection => _selection;

		// TODO 待加入图形对象的添加模块。
		public IShape Add()
		{
			throw new NotImplementedException();
		}

		public void Select(ISelectable obj)
		{
			Select(new[] { obj });
		}

		public void Select(IEnumerable<ISelectable> objRange)
		{
			UnSelectAll();

			foreach (var shape in objRange)
			{
				(shape as Shape).SelectForced();
				_selection.Add(shape);
			}
			OnSelectionChanged?.Invoke(
				this,
				new SelectionEventArgs(
					_selection,
					new ISelectable[] { },
					objRange));
		}


		public void SelectAdditional(ISelectable obj)
		{
			Select(new[] { obj });
		}

		public void SelectAdditional(IEnumerable<ISelectable> objRange)
		{
			foreach (var shape in objRange)
			{
				(shape as Shape).SelectForced();
				_selection.Add(shape);
			}


			OnSelectionChanged?.Invoke(
				this,
				new SelectionEventArgs(
					_selection,
					new ISelectable[] { },
					objRange));
		}

		public void UnSelect(ISelectable obj)
		{
			UnSelect(new[] { obj });
		}

		public void UnSelect(IEnumerable<ISelectable> objRange)
		{
			foreach (var shape in objRange)
			{
				(shape as Shape).UnSelectForced();
				_selection.Remove(shape);
			}

			OnSelectionChanged?.Invoke(
				this,
				new SelectionEventArgs(
					_selection,
					objRange,
					new ISelectable[] { }));
		}

		public void SelectAll()
		{
			foreach (var shape in this)
			{
				(shape as Shape).SelectForced();
				_selection.Add(shape);
			}

			OnSelectAll?.Invoke(this, this);
		}

		public void UnSelectAll()
		{

			foreach (var shape in this)
			{
				(shape as Shape).UnSelectForced();
			}
			_selection.Clear();

			LostSelectAll?.Invoke(this, this);
		}


		/// <summary>
		/// 强制且不触发事件地重置当前的选择容器内容。
		/// </summary>
		public void UnSelectAllForced()
		{
			foreach (var shape in this)
			{
				(shape as Shape).UnSelectForced();
			}
			_selection.Clear();
		}



	}
}
